﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuMianChaZhi.SurfaceInterpolation
{
    public class InterpolationMethodTwo : InterpolationMethod
    {
        private List<Point> mInitPoint;

        public double[,] CalculateInterpolation(List<Point> initPoints)
        {
            mInitPoint = initPoints;

            double[,] ret = new double[101, 101];

            for (int x = -50; x <= 50; x++)
            {
                for (int y = -50; y <= 50; y++)
                {
                    double z = CalculateValue(x, y);

                    ret[x + 50, y + 50] = z;
                }
            }

            return ret;
        }

        public double CalculateValue(double x, double y)
        {
            double z = CalculateDistance(x, y);

            if (z != -100)
            {
                return z;
            }

            List<Point> latest4Points = FindLatestFourPoint();


            double tz = 0.0;
            foreach(Point pt in latest4Points)
            {
                tz += pt.z;
            }

            return tz/latest4Points.Count;
        }

        /// <summary>
        /// 查找距离最近的四个点
        /// </summary>
        /// <returns></returns>
        private List<Point> FindLatestFourPoint()
        {
            Point[] points = mInitPoint.OrderBy(v => v.d).ToArray();

            List<Point> pt = new List<Point>();
            pt.AddRange(points.Take(3));

            return pt;
        }

        private double CalculateDistance(double x, double y)
        {
            foreach (var pt in mInitPoint)
            {

                pt.d = Math.Sqrt(Math.Pow((x - pt.x), 2) + Math.Pow((y - pt.y), 2));

                if (pt.d < 0.0000001 && pt.d > -0.000001)
                {
                    return pt.z;
                }
            }

            return -100;
        }
    }
}
